package com.longlong.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.longlong.config.WxGzhProperties;
import com.longlong.entity.WxGzhUser;
import com.longlong.mapper.WxGzhUserMapper;
import com.longlong.service.WxGzhUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;

@Service
public class WxGzhUserServiceImpl implements WxGzhUserService {

    @Autowired
    private WxGzhUserMapper wxGzhUserMapper;

    @Override
    public String getCode(String redirectUrl) {
        String url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ WxGzhProperties.WX_OPEN_APP_ID
                + "&redirect_uri="+ URLEncoder.encode(redirectUrl)
                + "&response_type=code"
                + "&scope=snsapi_base"
                + "&state=123#wechat_redirect";;
        return url;
    }


    /**
     * 插入openId
     * @param openid_gzh
     * @return
     */
    @Override
    public Object insertOpenId(String openid_gzh) {
        WxGzhUser wxGzhUser = new WxGzhUser();
        wxGzhUser.setOpenidGzh(openid_gzh);
        int result = wxGzhUserMapper.insert(wxGzhUser);
        return result;
    }

    /**
     * 判断是否需要插入openId
     * @param openId
     */
    @Override
    public void selectByOpenId(String openId) {
        QueryWrapper<WxGzhUser> wrapper = new QueryWrapper<>();
        wrapper.eq("openid_gzh",openId);
        Long i = wxGzhUserMapper.selectCount(wrapper);
        if(i<1){
            //2.如果数据库中存在则不需要在存储openid
            insertOpenId(openId);
        }
    }
}
